import { View, Text } from '@tarojs/components';
import { BasicLayout } from '@/layouts';
import { Empty, Icon } from '@/components';
import { Toast } from '@/utils/toast';
import { getApiChoiceChoiceCompany, getApiChoiceChoiceInfoId } from '@/api';
import { useRequest } from '@/hooks';
import { RouterUtil } from '@/utils';
import { usePreselectStore } from '@/models';
import dayjs from 'dayjs';
import './index.scss';
import { StorageKey } from '@/constants/storage';
import Taro from '@tarojs/taro';
import type { GetApiChoiceChoiceCompanyResponse } from '@/api';
const PreselectRecord = () => {
  const { clearAll, addDress, addPerson } = usePreselectStore();

  // 获取预选记录列表
  const { data: recordList = [], loading } = useRequest(
    getApiChoiceChoiceCompany,
  );

  // 获取预选详情
  const { run: fetchDetail } = useRequest(
    getApiChoiceChoiceInfoId,
    {
      manual: true,
      onSuccess: (data) => {
        // 清空当前预选数据
        clearAll();

        // 更新Store里的预选数据
        if (data?.orderDressDTOList && data.orderDressDTOList.length > 0) {
          data.orderDressDTOList.forEach((dress) => {
            addDress({
              id: dress.dressId || dress.id || 0,
              name: dress.dressName,
              dressType: dress.dressType,
              amount: dress.amount,
              size: dress.sizeName,
              pictureList: dress.pictureList,
              fileUrlList: dress.pictureList,
              orderType: dress.orderType,
              remark: dress.remark,
            });
          });
        }

        if (data?.bigFourDTOList && data.bigFourDTOList.length > 0) {
          data.bigFourDTOList.forEach((person) => {
            addPerson({
              id: person.id || 0,
              name: person.name,
              bigType: person.type,
              price: person.price || person.endPrice,
              phone: person.phone,
            });
          });
        }

        // 跳转到首页
        RouterUtil.switchTab('/pages/home/index/index');
      },
      onError: (error) => {
        Toast.info(error?.message || '获取预选详情失败');
      },
    }
  );

  // 处理进入店铺
  const handleEnterStore = (record?: GetApiChoiceChoiceCompanyResponse[0]) => {
    Taro.setStorageSync(StorageKey.SHOP_ID, record?.companyId);
    // fetchDetail({ id: record?.id as number });
    // 跳转到首页
    RouterUtil.switchTab('/pages/home/index/index');
  };

  // 格式化日期时间
  const formatDateTime = (dateStr?: string) => {
    if (!dateStr) return '';
    try {
      const date = dayjs(dateStr);
      if (date.isValid()) {
        // 格式化为 YY/MM/DD HH:mm，例如 "25/09/03 16:00"
        return date.format('YY/MM/DD HH:mm');
      }
      return dateStr;
    } catch (e) {
      return dateStr;
    }
  };

  return (
    <BasicLayout className="preselect-record-page" title="我的预选" back>
      {loading ? (
        <View className="loading-container">
          <Text className="loading-text">加载中...</Text>
        </View>
      ) : recordList.length === 0 ? (
        <View className="empty-container">
          <Empty description="暂无预选记录" />
        </View>
      ) : (
        <View className="record-list">
          {recordList.map((record) => (
            <View key={record.id} className="record-card" onClick={() => handleEnterStore(record)}>
              <View className="card-header">
                <Text className="store-name">{record.companyName || '未知店铺'}</Text>
              </View>
              <View className="card-footer">
                <Text className="record-date">{formatDateTime(record.createDate)}</Text>
                <View
                  className="enter-store-btn"
                >
                  <Text className="enter-store-text">进入店铺</Text>
                  <Icon name='RightOutlined' size={12} />
                </View>
              </View>
            </View>
          ))}
        </View>
      )}
    </BasicLayout>
  );
};

export default PreselectRecord;

